package com.aabte.lota.auth.account.controller;

import com.aabte.commons.rest.api.ApiResult;
import com.aabte.commons.rest.exception.ApiException;
import com.aabte.lota.auth.account.bean.enums.UserApiErrorCode;
import com.aabte.lota.auth.account.bean.query.UserQuery;
import com.aabte.lota.auth.account.entity.User;
import com.aabte.lota.auth.account.exception.UserAlreadyExistsException;
import com.aabte.lota.auth.account.service.UserService;
import io.swagger.annotations.Api;
import java.util.List;
import javax.annotation.Resource;
import javax.validation.Valid;
import org.apache.shiro.authz.annotation.RequiresGuest;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author Daniel
 * @version 1.0
 * @date 2020/3/29
 */
@Api
@RestController
@RequestMapping(value = "/v1/user")
public class UserController {

  @Resource private UserService userService;

  @RequiresRoles(value = "admin")
  @RequestMapping
  public ApiResult<List<User>> list() {
    List<User> users = userService.list();
    return ApiResult.ok(users);
  }

  @RequiresGuest
  @RequestMapping(path = "/register", method = RequestMethod.POST)
  public ApiResult<Long> register(@RequestBody @Valid UserQuery userQuery) {
    try {
      return ApiResult.ok(userService.add(userQuery));
    } catch (UserAlreadyExistsException e) {
      throw new ApiException(UserApiErrorCode.USER_ALREADY_EXISTS);
    }
  }
}
